package com.bdilab.iot.controller;

import com.bdilab.iot.annotation.CurrentUser;
import com.bdilab.iot.annotation.LogOperation;
import com.bdilab.iot.annotation.LogTag;
import com.bdilab.iot.common.ResultMap;
import com.bdilab.iot.consts.Constants;
import com.bdilab.iot.dto.userdto.CreateUserDto;
import com.bdilab.iot.dto.userdto.LoginResultDto;
import com.bdilab.iot.dto.userdto.UpdateUserDto;
import com.bdilab.iot.dto.userdto.UserDetail;
import com.bdilab.iot.enums.OperationType;
import com.bdilab.iot.model.User;
import com.bdilab.iot.service.UserService;
import com.bdilab.iot.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/8/1 17:10
 */
@RestController
@Api(tags = "用户管理")
@LogTag("用户管理")
@RequestMapping(value = Constants.BASE_API_PATH + "/user")
public class UserController {

    @Autowired
    TokenUtils tokenUtils;


    @Autowired
    UserService userService;


    @PostMapping("")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation("添加用户")
    @LogOperation(operationName = "添加用户", sensitiveParams = {"password"},operationType = OperationType.INSERT)
    public ResponseEntity addUser(
                                  @RequestBody @Valid CreateUserDto createUserDto,
                                  @ApiIgnore BindingResult bindingResult,
                                  HttpServletRequest request){

        if (bindingResult.hasErrors()) {
            ResultMap resultMap = new ResultMap().fail().message(bindingResult.getFieldErrors().get(0).getDefaultMessage());
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }
        LoginResultDto loginResultDto = userService.createUser(createUserDto);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request).payload(loginResultDto);
        return ResponseEntity.ok(resultMap);

    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation("注销用户")
    @LogOperation(operationName = "注销用户",operationType = OperationType.DELETE)
    public ResponseEntity deleteUser(@PathVariable("id") Long id,HttpServletRequest request){

        if(id <=1 ){
            ResultMap resultMap = new ResultMap(tokenUtils).failAndRefreshToken(request).message("无效的用户ID");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        userService.deleteUser(id);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request);

        return ResponseEntity.ok(resultMap);

    }

    @GetMapping("/{id}")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation("查询用户")
    @LogOperation(operationName = "查询用户",operationType = OperationType.SELECT)
    public ResponseEntity getUser(@PathVariable("id") Long id,HttpServletRequest request){

        if(id <=1 ){
            ResultMap resultMap = new ResultMap(tokenUtils).failAndRefreshToken(request).message("无效的用户ID");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        UserDetail userDetail = userService.getUserDetailByUserId(id);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request).payload(userDetail);

        return ResponseEntity.ok(resultMap);

    }

    @PutMapping("/{id}")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation("更改用户信息")
    @LogOperation(operationName = "更新信息",operationType = OperationType.UPDATE)
    public ResponseEntity updateUser(@PathVariable("id") Long id,
                                     @Valid @RequestBody UpdateUserDto updateUserDto,
                                     @ApiIgnore BindingResult bindingResult,
                                     HttpServletRequest request){
        if (bindingResult.hasErrors()) {
            ResultMap resultMap = new ResultMap().fail().message(bindingResult.getFieldErrors().get(0).getDefaultMessage());
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }
        if(id <=0 ){
            ResultMap resultMap = new ResultMap(tokenUtils).failAndRefreshToken(request).message("无效的用户ID");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        userService.updateUser(updateUserDto,id);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request);

        return ResponseEntity.ok(resultMap);

    }

    @GetMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    @ApiOperation("获取当前用户的全部个人信息")
    @LogOperation(operationName = "获取当前用户的全部个人信息", operationType = OperationType.SELECT)
    public ResponseEntity getMyProfile(HttpServletRequest request,
                                          @ApiIgnore @CurrentUser User user){
        UserDetail userDetail = userService.getMyUserDetail(user);

        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request).payload(userDetail);

        return ResponseEntity.ok(resultMap);
    }


}
